const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require("webpack");
const path = require('path');
const Dotenv = require('dotenv-webpack');
const {
  InjectManifest
} = require('workbox-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const px2rem = require('postcss-px2rem')
const webpackPlugins = [
  new HtmlWebpackPlugin({
    template: path.resolve(__dirname, 'public/index.html'),
    filename: 'index.html',
  }),
  new Dotenv({
    path: './.env-native', // Path to .env file (this is the default)
    systemvars: true,
  }),
  new CopyPlugin({
    patterns: [{
        from: './src/favicon.ico',
        to: ''
      },
      {
        from: './src/manifest.json',
        to: ''
      },
      {
        from: './src/logo192.png',
        to: ''
      },
      {
        from: './src/logo512.png',
        to: ''
      },
    ],
  }),
];

if ('production' === process.env.NODE_ENV) {
  webpackPlugins.push(new InjectManifest({
    swSrc: './src/src-sw.js',
    swDest: 'sw.js',
  }));
}

module.exports = {
    context: __dirname,
    entry: './src/index.js',
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: '[name].[chunkhash].js',
      publicPath: '/',
    },
    devServer: {
      historyApiFallback: true,
    },
    optimization: {
      splitChunks: {
        chunks: 'async',
        minSize: 20000,
        minRemainingSize: 0,
        minChunks: 1,
        maxAsyncRequests: 30,
        maxInitialRequests: 30,
        enforceSizeThreshold: 50000,
        cacheGroups: {
          defaultVendors: {
            test: /[\\/]node_modules[\\/]/,
            priority: -10,
            reuseExistingChunk: true,
          },
          default: {
            minChunks: 2,
            priority: -20,
            reuseExistingChunk: true,
          },
        },
      },
    },
    module: {
      rules: [{
          test: /\.js$/,
          use: 'babel-loader',
        },
        {
          test: /\.(png|j?g|svg|gif)?$/,
          use: 'file-loader?name=./images/[name].[ext]',
        },
        {
          test: /\.scss$/,
          exclude: /node_modules/,
          use: [
            "style-loader",
            "css-loader",
            "sass-loader",
            "postcss-loader",
          ],
        },
    ],
  },
  plugins: webpackPlugins,
};